#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License 2.1 or later, as
 * published by the Free Software Foundation. See the included License.txt
 * or http://www.gnu.org/copyleft/lesser.html for details.
 * 
 * Author: Billy Zhang
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Net;
using System.IO;
using System.Web.UI.WebControls;
using CchenSoft.Portal.Model;
using CchenSoft.Portal.Service;
using CchenSoft.Portal.Registry;
using CchenSoft.Portal.Util;
using System.Web;
using CchenSoft.Portal.Spi.Registry;

namespace CchenSoft.Portal.Web
{
    [ParseChildren(true)]
    public class MaxControl : ChildControl
    {
        protected override void InitializeSkin(Control control)
        {
            string hostName = GetHostName();
            
            Control column = control.FindControl("column");

            PortalURL portalURL = PortalContext.Current.PortalURL;
            int maxInstance = portalURL.GetMaxInstance();
            if (maxInstance > 0)
            {
                PortletInstance pi = ServiceLocator.PortalService.LoadPortletInstance(maxInstance);
                Control view = new PortletControl(hostName, pi);
                column.Controls.Add(view);
            }
            else
            {
                string portletName = portalURL.GetMaxPortlet();
                PortletEntry entry = PortalRegistry.Instance.GetPortlet(portletName);
                Control view = new SingleControl(hostName, entry);
                column.Controls.Add(view);
            }
        }

        protected override Control LoadSkin()
        {
            Control control = Page.LoadControl(LayoutRegistry.Instance.MaxLayout.TemplatePath);
            return control;
        }

        private string GetHostName()
        {
            string hostName;

            if (Page.Request.Url.Port == 80)
                hostName = "http://" + Page.Request.Url.Host;
            else
                hostName = "http://" + Page.Request.Url.Host + ":" + Page.Request.Url.Port;

            return hostName;
        }
    }
}
